﻿using Autofac.Integration.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel.Configuration;
using System.Text;
using System.Timers;
using System.Xml;
using System.Web.Mvc;

namespace CNKI.TPI.Web.Base
{
    public class ConfigHelper
    {
        private static Hashtable accessConfig = null;
        private static Timer timer = null;

        public static void Init()
        {
            int AccessConfigUpdate = GetAccessConfigUpdateIntervalTime();
            if (-1 != AccessConfigUpdate)
            {
                accessConfig = new Hashtable();
                UpdateAccessConfig(null, null);
                timer = new Timer();
                timer.Interval = GetAccessConfigUpdateIntervalTime();
                timer.Elapsed += UpdateAccessConfig;
                timer.Enabled = true;
            }
        }

        public static string GetAppSettingsValue(string key)
        {
            ConfigurationManager.RefreshSection("appSettings");
            return ConfigurationManager.AppSettings[key] ?? string.Empty;
        }

        public static string GetConnSettingsValue(string key)
        {
            ConfigurationManager.RefreshSection("connectionStrings");
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[key];
            return settings.ConnectionString;
        }

        public static bool IsDrsConfigExsit()
        {
            bool result = false;
            var config = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
            if (config.Endpoints.Count != 0)
            {
                result = true;
            }
            return result;
        }

        public static bool IsShowSQLEnabled()
        {
            return GetAppSettingsValue("ShowSql") == "true" ? true : false;
        }

        public static bool IsHtmlEscape()
        {
            return GetAppSettingsValue("HTMLEscape") == "true" ? true : false;
        }

        public static bool IsSpaceEscape()
        {
            return GetAppSettingsValue("SpaceEscape") == "true" ? true : false;
        }

        public static bool IsSmartwordEnabled()
        {
            return GetAppSettingsValue("smartWordEnable") == "true" ? true : false;
        }

        public static bool IsAnonymousControlEnabled()
        {
            return GetAppSettingsValue("AnonymousControl") == "true" ? true : false;
        }

        public static bool UseORMInUnionDBSearchEnabled()
        {
            return GetAppSettingsValue("UseORMInUnionDBSearch") == "1" ? true : false;
        }

        public static string GetAnonymousAccount()
        {
            return GetAppSettingsValue("AnonymousAccount");
        }

        public static string GetSmartwordAddress()
        {
            return GetAppSettingsValue("smartWordAddress");
        }

        public static string GetCNKIResourceHost()
        {
            return GetAppSettingsValue("CNKIResourceHost");
        }

        public static string GetCNKIResourceKey()
        {
            return GetAppSettingsValue("CNKIResourceKey");
        }

        public static string GetKspiderHost()
        {
            return GetAppSettingsValue("KspiderHost");
        }

        public static string GetKspiderKey()
        {
            return GetAppSettingsValue("KspiderKey");
        }

        public static bool IsWebApiAccessControlEnabled()
        {
            return GetAppSettingsValue("AccessControlEnabled") == "true" ? true : false;
        }

        public static bool IsShowUserHistoryEnabled()
        {
            return GetAppSettingsValue("ShowUserHistory") == "true" ? true : false;
        }

        public static bool IsWebApiLoginControlEnabled()
        {
            return GetAppSettingsValue("LoginControl") == "true" ? true : false;
        }

        public static bool IsEncryptPasswordEnabled()
        {
            return GetAppSettingsValue("EncryptPassword") == "true" ? true : false;
        }
        public static string GetSiteTitle()
        {
            return GetAppSettingsValue("SiteTitle");
        }

        public static int GetWebApiLoginSessionTimeout()
        {
            int result = 0;
            string config = GetAppSettingsValue("WebApiSessionTimeout");
            if (!string.IsNullOrEmpty(config))
            {
                result = int.Parse(config);
            }
            return result;
        }

        public static int GetAccessConfigUpdateIntervalTime()
        {
            int result = -1;
            string config = GetAppSettingsValue("AccessConfigUpdateIntervalTime");
            if (!string.IsNullOrEmpty(config))
            {
                result = int.Parse(config);
            }
            return result;
        }

        public static string GetAccessConfig(string from)
        {
            string result = "";
            if (accessConfig != null && accessConfig.ContainsKey(from))
            {
                result = accessConfig[from].ToString();
            }
            return result;
        }

        private static void UpdateAccessConfig(object sender, ElapsedEventArgs e)
        {
            IDataContext context = AutofacDependencyResolver.Current.GetService<IDataContext>();
            string sql = "SELECT AccessConfigName, AccessConfigKey FROM tpi.accessconfig where AccessConfigStatus = 1";
            DataTable dt = context.ExecuteSql(sql, "mysql");
            if (null != dt)
            {
                accessConfig.Clear();
                foreach (DataRow dr in dt.Rows)
                {
                    accessConfig.Add(dr["AccessConfigName"], dr["AccessConfigKey"]);
                }
            }
        }

        public static int GetDataCacheTimeout()
        {
            int result = 0;
            string config = GetAppSettingsValue("DataCacheTimeout");
            if (!string.IsNullOrEmpty(config))
            {
                result = int.Parse(config);
            }
            return result;
        }

        public static int GetCategoryCacheTimeout()
        {
            int result = 0;
            string config = GetAppSettingsValue("CategoryCacheTimeout");
            if (!string.IsNullOrEmpty(config))
            {
                result = int.Parse(config);
            }
            return result;
        }

        public static int GetSearchResultCutLengh()
        {
            int result = 30;
            string config = GetAppSettingsValue("SearchResultCutLengh");
            if (!string.IsNullOrEmpty(config))
            {
                result = int.Parse(config);
            }
            return result;
        }

        public static string GetSmartTag()
        {
            return GetAppSettingsValue("SmartTag");
        }

        public static IDictionary<string, int> GetExtDataSourceList()
        {
            IDictionary<string, int> result = new Dictionary<string, int>();
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "ExtDataSource.config");
                XmlNode xn = doc.SelectSingleNode("DataSourceList");
                // 得到根节点的所有子节点
                XmlNodeList xnl = xn.ChildNodes;
                foreach (XmlNode xn1 in xnl)
                {
                    XmlElement xe = (XmlElement)xn1;
                    string dsName = xe.GetAttribute("name").ToString();
                    string dsType = xe.GetAttribute("value").ToString();
                    result.Add(dsName, int.Parse(dsType));
                }
            }
            catch(Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        public static bool IsOAAccountEnabled()
        {
            return GetAppSettingsValue("EnabledOAAccount") == "true" ? true : false;
        }

        public static string GetOAAccountURL()
        {
            return GetAppSettingsValue("OAAccountURL");
        }

        public static string GetExternalMenu()
        {
            return GetAppSettingsValue("ExternalMenu");
        }

        public static bool IsTopicMenuEnabled()
        {
            return GetAppSettingsValue("TopicMenu") == "true" ? true : false;
        }

        public static bool IsSSOEnabled()
        {
            return GetAppSettingsValue("Enabled_SSO") == "true" ? true : false;
        }

        public static bool IsAutoShowResult()
        {
            return GetAppSettingsValue("SingleSearch_Auto_Load_Result") == "true" ? true : false;
        }

        public static string GetFileServerUrl()
        {
            return GetAppSettingsValue("FileServerUrl");
        }

    }
}
